<?php
declare (strict_types = 1);

namespace app\common\libs\upload;

use app\common\model\AttachmentModel;
use Exception;
use OSS\Core\OssException;
use OSS\OssClient;

/**
 * OSS上传
 *
 * @Author tanruizheng
 * @DateTime 2021-07-19
 */
class Aliyun extends UploadDriver
{

    private $accessKeyId;//OSS-accessKeyId
    private $accessKeySecret;//accessKeySecret
    private $endpoint;//OSS-Endpoint
    private $bucket;//OSS-bucket

    public function __construct($config)
    {
        if($config['siteurl'] == '' || $config['siteurl'] == '/'){
            $this->siteurl = request()->domain();
        }else{
            $this->siteurl = $config['siteurl'];
        }
        $this->accessKeyId = $config['attachment_aliyun_key_id'];
        $this->accessKeySecret = $config['attachment_aliyun_key_secret'];
        $this->endpoint = $config['attachment_aliyun_endpoint'];
        $this->bucket = $config['attachment_aliyun_bucket'];
        $this->domain = $config['attachment_aliyun_domain'];
    }

    /**
     * OSS上传
     *
     * @Author tanruizheng
     * @DateTime 2021-07-19
     * @param AttachmentModel $attachment
     * @return object
     */
    public function upload(AttachmentModel $attachment){
        $file = request()->file('file');
        // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        $filePath = $file->getPath().'/'.$file->getFilename();
       // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = $this->endpoint;
        // 设置存储空间名称。
        $bucket= $this->bucket;
        // 设置文件名称。
        $object = $attachment->module.'/'.date('Ymd').'/'.md5(time().rand(1000,9999)).'.'.$attachment->fileext;
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $options = [];
            if($attachment->module == AttachmentModel::MODULE_IMAGE){
                $options = [
                    OssClient::OSS_CONTENT_TYPE => 'image/'.$attachment->fileext,
                ];
            }
            $res = $ossClient->uploadFile($bucket, $object, $filePath, $options);
            if($res['oss-request-url']){
                $attachment->filepath = $object;
                $attachment->fileurl = $res['oss-request-url'];
                //视频截帧
                if($attachment->module == AttachmentModel::MODULE_VIDEO){
                    $attachment->filethumb = $attachment->getData('fileurl').'?x-oss-process=video/snapshot,t_500,f_jpg';
                }
                $ossClient->putObjectAcl($bucket,$object,OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
            }else{
                throw new \Exception('文件上传失败!');
            }
        } catch(OssException $e) {
            throw new \Exception($e->getMessage());
        }
        return true;
    }
}
